<?php
// websocket_server.php
use Workerman\Lib\Timer;
use Workerman\Worker;

require_once __DIR__ . '/vendor/autoload.php';

// 创建一个 WebSocket 服务器，监听 9501 端口
$ws_worker = new Worker("websocket://0.0.0.0:9501");

// 设置进程数
$ws_worker->count = 4;

// 当有客户端连接时
$ws_worker->onConnect = function ($connection) {
    echo "New connection\n";
};

$ws_worker->onWorkerStart = function($worker)
{
    // 开启一个内部端口，方便内部系统推送数据，Text协议格式 文本+换行符
    $inner_text_worker = new Worker('Text://0.0.0.0:5678');
    $inner_text_worker->onMessage = function($connection, $buffer)
    {
        $ret = broadcast($buffer);
        // 返回推送结果
        $connection->send($ret ? 'ok' : 'fail');
    };
    $inner_text_worker->listen();
};
function broadcast($message)
{
    global $ws_worker;
    foreach($ws_worker->connections as $connection)
    {
        $connection->send($message);
    }
    return true;
}

// 当有客户端发送消息时
$ws_worker->onMessage = function ($connection, $data) use ($ws_worker) {
    // 处理接收到的消息
    echo "Received message: $data\n";

    // 广播消息给所有连接的客户端
    foreach ($ws_worker->connections as $client) {
        $client->send($data);
    }
};

// 当客户端断开连接时
$ws_worker->onClose = function ($connection) {
    echo "Connection closed\n";
};

// 运行 Worker
Worker::runAll();
